package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired(required = false)
    private DishService dishService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto, HttpSession session){
        long empId = (long)session.getAttribute("employee");
        dishDto.setCreateUser(empId);
        dishDto.setCreateTime(LocalDateTime.now());
        dishDto.setUpdateTime(LocalDateTime.now());
        dishDto.setUpdateUser(empId);
        dishService.saveWithFlavor(dishDto);
        return R.success("新菜品添加成功");
    }

    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page,Integer pageSize,String name){
       Page<DishDto> pageResult = dishService.page(page,pageSize,name);
       return R.success(pageResult);
    }

    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }


    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishDto,HttpSession session){
        long empId = (long) session.getAttribute("employee");
        dishDto.setUpdateUser(empId);
        dishDto.setUpdateTime(LocalDateTime.now());
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Long categoryId,Integer status){
        List<DishDto> dishList = dishService.findByCategoryId(categoryId,status);
        return R.success(dishList);
    }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        dishService.deleteByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 批量停售
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status,@RequestParam List<Long> ids,HttpSession session){
        Long empId = (Long) session.getAttribute("employee");


        DishDto dishDto = new DishDto();
        dishDto.setUpdateTime(LocalDateTime.now());
        dishDto.setUpdateUser(empId);

        dishService.updateStatus(ids,dishDto,status);
        return R.success("更改成功");
    }

}
